/************************************************************/
/*
	File: CrudGenerator.java

	CrudGenerator reads an service schema definition and
	generates a set of services.

	Author: James Cowan
*/
/************************************************************/

package org.ems.crud;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.ems.crud.model.CrudServiceList;
import org.ems.generator.Generator;
import org.ems.generator.GeneratorException;
import org.ems.generator.IGenerator;
import org.ems.generator.IGeneratorOutput;

/************************************************************/

abstract public class CrudGenerator extends Generator implements IGenerator
{
	protected CrudServiceList		m_crudServiceList;

	static protected Logger		m_log = Logger.getLogger(CrudGenerator.class);
	
	public CrudGenerator(File schemaDirectory, File schemaFile, File output)
	throws GeneratorException
	{
		super(schemaDirectory, schemaFile, output);
		
		m_crudServiceList = getCrudServiceList();
	}

	/************************************************************/
	/* public methods */
	/************************************************************/
	/** generate */

	public void generate(IGeneratorOutput output) throws IOException, GeneratorException
	{
		if (!m_schemaFile.exists())
		{
		String msg = m_schemaFile.getAbsolutePath()+" is missing";
		
			throw new GeneratorException(msg);		
		}
				
		FileUtils.forceMkdir(m_output);
		
		m_log.info("Create ui: "+m_output.getAbsolutePath());
		
		generateUI();

	} // generate
	
	/************************************************************/
	/* protected methods */
	/************************************************************/
	/** createUIGenerator */
	
	abstract protected CrudUIGenerator	createUIGenerator();
	
	/************************************************************/
	/** generateUI */
	
	protected void generateUI() throws IOException, GeneratorException
	{
	CrudUIGenerator generator = createUIGenerator();	
	
		generator.generate();
			
	} // generateUI
	
	/************************************************************/
	/** getCrudServiceList */
	
	protected CrudServiceList getCrudServiceList()throws GeneratorException
	{	
        try
        {
        FileReader fr = new FileReader(m_schemaFile);
        	
        	return CrudServiceList.unmarshal(fr);
        }
        catch (Throwable e)
        {
        String schemaFileName = m_schemaFile.getAbsolutePath();
        String msg = "Cannot read "+schemaFileName+": "+e.getMessage();
        	
        	throw new GeneratorException(msg);
        }
        	
	} // getCrudServiceList
	
} // CrudGenerator

/************************************************************/


